import logger from '../services/logger.js'
import { modelService } from '../services/model.js'

// 生成文本嵌入向量
export async function generateEmbeddings(texts) {
  try {
    if (!Array.isArray(texts)) {
      texts = [texts]
    }

    logger.info('Generating embeddings:', {
      count: texts.length,
      firstTextLength: texts[0]?.length
    })

    const embeddings = await Promise.all(
      texts.map(async text => {
        try {
          const embedding = await modelService.generateEmbedding(text)
          return embedding
        } catch (error) {
          logger.error('Failed to generate embedding:', {
            error: error.message,
            textLength: text.length
          })
          throw error
        }
      })
    )

    logger.info('Generated embeddings:', {
      count: embeddings.length,
      dimension: embeddings[0]?.length
    })

    return embeddings
  } catch (error) {
    logger.error('Failed to generate embeddings:', error)
    throw error
  }
}

// 批量生成嵌入向量
export async function batchGenerateEmbeddings(texts, batchSize = 32) {
  try {
    const batches = []
    for (let i = 0; i < texts.length; i += batchSize) {
      batches.push(texts.slice(i, i + batchSize))
    }

    logger.info('Processing batches:', {
      totalTexts: texts.length,
      batchCount: batches.length,
      batchSize
    })

    const embeddings = []
    for (const batch of batches) {
      const batchEmbeddings = await generateEmbeddings(batch)
      embeddings.push(...batchEmbeddings)
    }

    return embeddings
  } catch (error) {
    logger.error('Failed to batch generate embeddings:', error)
    throw error
  }
} 